<?php

namespace backend\controllers;

use common\components\BController;
use backend\models\MY_Dirfile;
use common\components\MTools;
use yii\helpers\Url;
use yii\helpers\Json;
use Yii;

class FileController extends BController {

    public function actions() {
        return [
            "list" => [
                "class" => "\common\actions\ListAction",
                "modelClass" => new MY_Dirfile()
            ],
            "create" => [
                "class" => "\common\actions\CreateAction",
                "modelClass" => new MY_Dirfile(),
                "renderParams" => ["action" => "create"],
            ],
            "update" => [
                "class" => "\common\actions\UpdateAction",
                "modelClass" => new MY_Dirfile(),
                "renderTo" => "create",
                "renderParams" => [ "action" => "update"]
            ]
        ];
    }
    /*
     * ajax文件数据列表
     */

    public function actionAjaxfilelist() {
        $res = MY_Dirfile::getList();
        $temp = ["total" => $res["total"], "rows" => []];
        if ($res["total"] > 0) {
            foreach ($res["data"] as $item) {
                $temp["rows"][] = [
                    "id" => $item["id"],
                    "title" => $item["title"],
                    "name" => $item["name"],
                    "url" => \yii\helpers\Html::a($item["name"], MY_Dirfile::getFilePath($item["name"])),
                    "action" => MTools::getStringActions([
                        "update" => [
                            "params" => [ "id" => $item["id"]],
                            "title" => "编辑"
                        ],
                        "deletefile" => [
                            "params" => [ "id" => $item["id"]],
                            "title" => "删除"
                        ]
                    ])
                ];
            }
        }
        echo Json::encode($temp);
    }

    /*
     * 删除文件
     */

    public function actionDeletefile() {
        $id = Yii::$app->request->get("id");
        if (MY_Dirfile::deleteData($id)) {
            Yii::$app->getSession()->setFlash('success', '删除成功！');
            $this->redirect(["list"]);
        } else {
            Yii::$app->getSession()->setFlash('error', '删除失败！');
        }
    }
}
